const express = require("express");
const db = require("../config");

const commentRouter = express.Router();

/* 发布评论 */
commentRouter.post("/addComment", (req, res) => {
    const {goodid,userid,orderid,size,color,content} = req.body;
    const sql = "insert into db_comment(goodsId,userId,orderId,goodsSize,goodsColor,content) values(?,?,?,?,?,?)";
    db.query(sql,[goodid,userid,orderid,size,color,content],(err,result)=>{
        if(err) return res.fail(err.message);
        if(result.affectedRows!==1) return res.fail("发布失败，请重试");
        res.send({
            status:0,
            message:"发布评论成功"
        })
    })
});



/* 删除指定用户的评论 */
commentRouter.post("/delComment", (req, res) => { 
    const sql = "delete from db_comment where id=?";
    db.query(sql,req.body.id,(err,result)=>{
        if(err) return res.fail(err.message);
        if(result.affectedRows!==1) return res.fail("删除评论失败，请重试");
        res.send({
            status:0,
            message:"删除评论成功"
        })
    })
 })


 /* 获取指定商品评论 */
commentRouter.get("/getAllComm",(req,res)=>{
    const sql = "SELECT c.id,c.goodsId,c.userId,c.orderId,g.name AS goodsName,g.imgSrc AS goodsImg,c.goodsSize AS size,c.goodsColor AS color,c.content,c.create_at,u.username FROM db_comment c JOIN db_goods g ON c.goodsId = g.id JOIN db_users u ON c.userId = u.userId WHERE c.goodsId=?;"
    db.query(sql,req.query.goodsId,(err,result)=>{
        if(err) return res.fail(err.message);
        if(result.length<=0) return res.fail("获取评论失败");
        res.send({
            status:0,
            message:"获取评论成功",
            data:result
        })
    })
})

/* 获取所有评论 */
commentRouter.get("/getAllComments",(req,res)=>{
    const sql = "SELECT c.id,c.goodsId,c.userId,c.orderId,g.name AS goodsName,g.imgSrc AS goodsImg,c.goodsSize AS size,c.goodsColor AS color,c.content,c.create_at,u.username FROM db_comment c JOIN db_goods g ON c.goodsId = g.id JOIN db_users u ON c.userId = u.userId;"
    db.query(sql,(err,result)=>{
        if(err) return res.fail(err.message);
        if(result.length<=0) return res.fail("获取所有评论失败");
        res.send({
            status:0,
            message:"获取所有评论成功",
            data:result
        })
    })
})

module.exports = { commentRouter };